<?php

namespace App\Controllers;
class NovelController extends Collect
{

    //http://www.mzhu8.com/mulu/11/1.html


    public function handle($param = null)
    {
        resolve('mysql')::instance();
        $this->initParam($param);                               //初始化参数
        $this->initHost();                                      //初始化主机参数
  //      if(! $this->mkdir()); // return;                      //创建文件夹
        $this->saveNovel();                                     //保存小说
        $this->initUrls();                                      //要采集的章节
        $this->httpFileUrl();                                   //转换url
        $this->writeFile();                                     //写入文件
    }

    protected $novel;
    public function saveNovel()
    {
        $content = resolve('request')->send($this->url);
        $data = [
        'name' => resolve('match')->raw('<h1>(.*?)<\/h1>',$content),
        'description' => resolve('match')->raw('id="fmimg">.*?<p>(.*?)<\/p>',$content),
        'cover' => resolve('match')->raw('<img.*?src="(.*?)"',$content),
        'type' => 'mingzhu',
        'source_link' => $this->url.(string)rand(1,9787887),
        'hot' => 0,
        'sort' => 0,
        'is_over' => 1,
        'author_id' => 1
        ];
        resolve('mysql')->table('novels')->save($data);


    }


    public function initUrls()
    {
        $content = resolve('request')->send($this->url);
        $href = resolve('match')->findHref($content);
        $this->urls = $this->filterUrl($href);
    }


    public function filterUrl($urls)
    {
        $all = [];
        foreach ($urls as $url){
            if( preg_match('/book\/\d.*?html/',$url))
                $all[] = $url;
        }
        unset($all[0]);
        return $all;
    }


    public function writeFile()
    {


        foreach ($this->urls as $k=>$url){
          $content = resolve('request')->send(
              $this->http_type.'://'.$this->host.'/modules/article/show.php',
              'POST',
              ['aid' => 106,'cid'=>2247],'utf-8'
          );

          dd($content);
        }

    }

}

